<script lang="ts" setup>
  import { defineProps, ref, watch, defineEmits, onMounted } from "vue"
  import { getCustomDepartmentList } from "@/api/custom"

  const props = defineProps(['modelValue','width']);
  const emit = defineEmits(['update:modelValue', 'change']);

  const list = ref([])
  const data = ref<any>(props.modelValue)

  // 获取列表数据并处理初始值
  const initData = async () => {
    try {
      const res = await getCustomDepartmentList({currentPage: 1,pageSize: 999999})
      list.value = res.data
      
      // 如果有初始值，查找对应的选项并触发change事件
      if (props.modelValue) {
        const selectedItem = list.value.find(item => item.customId === props.modelValue)
        if (selectedItem) {
          emit('change', {
            value: selectedItem.customId,
            isNewOption: false,
            name: selectedItem.name
          })
        }
      }
    } catch (error) {
      console.error('获取客户列表失败:', error)
    }
  }

  const change = (e) => {
    // 判断是否为新增选项
    const isNewOption = !list.value.some(item => item.customId === e)
    
    if (isNewOption) {
      emit('change', {
        value: e,
        isNewOption: true,
        name: e
      })
    } else {
      const selectedItem = list.value.find(item => item.customId === e)
      emit('change', {
        value: e,
        isNewOption: false,
        name: selectedItem?.name
      })
    }
    emit('update:modelValue', e)
  }

  watch(
    () => props.modelValue,
    (newVal, oldVal) => {
      data.value = newVal
    }
  )

  // 组件挂载时初始化数据
  onMounted(() => {
    initData()
  })
</script>

<template>
  <el-select 
    :style="`width: ${!width ? '200px' : width}`" 
    v-model="data" 
    placeholder="请选择" 
    @change="change" 
    clearable
    filterable
    allow-create
    default-first-option>
    <el-option 
      v-for="item in list" 
      :key="item.customId"
      :label="item.name" 
      :value="item.customId">
    </el-option>
  </el-select>
</template>

<style lang="scss" scoped>

</style>
